package com.gin.no_gay_alliance.manager;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;

/**
 * 通知推送工具类
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/7/15 17:05
 **/
public class NotificationUtils {
    private static final String CHANNEL_NAME_PREFIX = "CHANNEL_NAME_";
    private static NotificationUtils notificationUtils;
    private final NotificationManager manager;

    public NotificationUtils(Context context) {
        this.manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static NotificationUtils getInstance(Context context) {
        if (notificationUtils == null) {
            notificationUtils = new NotificationUtils(context);
        }
        return notificationUtils;
    }

    /**
     * 获取通知通道，如果不存在指定id的通道，使用默认配置创建一个新的
     *
     * @param channelId 通道id
     * @return 通道
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public NotificationChannel getChannel(String channelId) {
        NotificationChannel channel = manager.getNotificationChannel(channelId);
        if (channel != null) {
            return channel;
        }
        channel = new NotificationChannel(channelId, CHANNEL_NAME_PREFIX + channelId, NotificationManager.IMPORTANCE_DEFAULT);
        addChannel(channel);
        return channel;
    }

    /**
     * 添加通知通道
     *
     * @param notificationChannel 通知通道
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void addChannel(NotificationChannel notificationChannel) {
        manager.createNotificationChannel(notificationChannel);
    }

    /**
     * 发布一个通知
     *
     * @param notification 通知
     * @return 发布id
     */
    public void publish(int id, Notification notification) {
        manager.notify(id, notification);
    }

    /**
     * 取消一个通知
     *
     * @param id 发布id
     */
    public void cancel(int id) {
        manager.cancel(id);
    }

    public NotificationManager getManager() {
        return manager;
    }
}